from utilsapp import utils
import os
import time
import traceback
import uuid
from flask import Blueprint, current_app, request
import pandas
from utilsapp.mysql_con import db_connect, db_insert_id
from utilsapp.mysql_con import db_operation
from utilsapp.mysql_con import (
    db_delete,
    db_insert,
    db_fetchone,
    db_update,
    db_table_pagelist,
)

role = Blueprint("role", __name__)
tableName = "role"


# 查看所有有效角色
@role.route("/getlist", methods=["post"])
def table_list():
    if "page" in request.json.keys() and "size" in request.json.keys():
        page = request.json["page"]
        size = request.json["size"]
    else:
        page = 1
        size = 999
    j = db_table_pagelist(tableName, page, "", size)
    return j


# 添加角色
@role.route("/add", methods=["POST"])
def role_add():
    return db_insert(tableName, request.json)


# 删除角色
@role.route("/delete", methods=["POST"])
def role_delete():
    id = request.json["id"]
    return db_delete(tableName, f"WHERE id=%s", {"id": id})


# 修改角色
@role.route("/edit", methods=["POST"])
def role_edit():
    id = request.json["id"]
    keys_not_add = ["id"]
    addModel = {
        key: request.json[key] for key in request.json if key not in keys_not_add
    }
    return db_update(tableName, addModel, f"WHERE id=%s", {"id": id})


@role.route("/permissions", methods=["get"])
def role_permissions():
    size = int(request.args.get("size"))
    page = int(request.args.get("page"))
    s1 = f"select * from permissions LIMIT {max(0, (page - 1) * size)},{size}"
    res = db_connect(s1)
    s2 = "select count(*) as num from permissions"
    res1 = db_connect(s2)
    res["pagination"] = {
        "page": page,
        "pageSize": size,
        "total": res1["data"][0]["num"],
    }
    return res


@role.route("/upload", methods=["POST"])
def upload():
    try:
        # 检查请求中是否包含文件
        if "file" not in request.files:
            return utils.fail("空文件")
        file = request.files["file"]
        # 检查文件是否为空
        if file.filename == "":
            return utils.fail("空文件")
        script_dir = os.path.dirname(os.path.abspath(__name__)) + "/static"
        date = time.strftime("%Y%m%d", time.localtime())
        ext = os.path.splitext(file.filename)[-1]

        if "xls" not in ext:
            return utils.fail(None, "导入失败,文件格式不正确")

        fileName = f"/upload/{date}"
        filePath = script_dir + fileName
        if not os.path.exists(filePath):
            os.mkdir(filePath)

        fileName = f"/upload/{date}/{uuid.uuid1()}{ext}"
        filePath = script_dir + fileName

        # 保存文件到指定目录
        file.save(filePath)
        df = pandas.read_excel(filePath)
        row_count = len(df)
        if row_count <= 0:
            return utils.fail("excel 暂无数据")
        l = []
        for i in range(row_count):
            row = df.loc[i]
            if str(row["角色"]) != "nan":
                l.append(row["角色"])
        l = list(set(l))
        for index, item in enumerate(l):
            data = {
                "id": 1000 + index,
                "name": "建水公司" + item,
                "desc": "建水公司" + item,
                "dataId": 0,
                "warnpermission": 1,
                "menu": "1,2,3,4,33,41,45,5,10,49,50,51,53,6,11,47,55,56,7,27,30,9,46,48,12,13,14,15,16,17,18,32,34,37,44,58,19,20,21,22,23,24,25,26,28,31,38,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122",
                "operate": 1,
            }
            print(db_insert_id(tableName, data), index)
        return utils.ok("")
    except Exception as e:
        error_message = traceback.format_exc()
        current_app.add_log("测点导入", error_message)
        return utils.fail(None, "导入失败", e)
